﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Boomerang.Common.Configuration;
using System.Threading;

namespace Boomerang.Management.UIControlers
{
    public class ConfigurationListView
    {

        private string[] cols = new string[] { "Organization Name", "Discovery Server Url", "Authentication Mode" };

        private ListView lv;

        public ConfigurationListView(ListView lv)
        {
            this.lv = lv;

            lv.Items.Clear();

            lv.View = View.Details;

            lv.Columns.Clear();
            foreach (string item in cols)
            {
                lv.Columns.Add(item);
            }

            PopulateColumns();

            ConfigurationManager.OnConfigurationChange += new ConfigurationChangeEventHandler(ConfigurationManager_OnConfigurationChange);            
        }

        private void PopulateColumns()
        {
            if (lv.InvokeRequired)
            {
                lv.Invoke(new ThreadStart(delegate() { PopulateColumns(); }), null);
                return;
            }
            lv.Items.Clear();

            foreach (Organization org in ConfigurationManager.GetAllOrganizations())
            {
                ListViewItem item = new ListViewItem(org.CrmConnectionOptions.OrgName);
                item.SubItems.Add(org.CrmConnectionOptions.GetCrmDiscoveryServiceUrl());
                item.SubItems.Add(org.CrmConnectionOptions.AuthMode.ToString());
                item.Tag = org;
                lv.Items.Add(item);
            }
            
            lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }


        void ConfigurationManager_OnConfigurationChange()
        {
            PopulateColumns();
        }


    }
}
